package com.gitee.form_token.token;

import com.gitee.form_token.annotation.AppLogin;
import com.gitee.form_token.common.RedisUtil;
import com.gitee.form_token.entity.AppUser;
import org.springframework.lang.NonNull;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AppInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {

        AppLogin annotaion = null;

        // 判断注解 -- 没有 @AppLogin 则放行
        if (handler instanceof HandlerMethod) {
            annotaion = ((HandlerMethod) handler).getMethodAnnotation(AppLogin.class);
        } else {
            return true;
        }

        if (annotaion == null) {
            return true;
        }

        // Token校验
        String username = CheckAppToken.getSubject(request);
        String redisKey = "app_" + username;

        AppUser appUser = (AppUser) redisUtil.get(redisKey);
        if (appUser == null) {
            throw new RuntimeException("redis读取失败");
        }

        System.out.println("AppLogin==" + appUser);

        return true;
    }
}
